package cn.zyy.jdbc;

import cn.zyy.entity.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo03 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            //1、注册驱动  方式2  类加载  反射  推荐
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            String url = "jdbc:mysql://localhost:3306/java2114";
            String username = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url, username, password);
            //3、生成操作数据库的对象
            stmt = conn.createStatement();
            //4、编写SQL 发送SQL DML insert delete update
            User user = new User();
            user.setRole(1);
            user.setPwd("123456");
            user.setUsername("赵六");
            String sql = "insert into user(username,pwd,role) values('"+user.getUsername()+"','"+user.getPwd()+"',"+user.getRole()+")";
            //5、处理结果集
            //影响的行数
            int line = stmt.executeUpdate(sql);
            String result = line == 1 ? "成功" : "失败";
            System.out.println(result);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6、释放资源
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
